<template>
    <el-dialog 
      title="创建文章" 
      :visible.sync="visible"
      width="80%"
      class="create-modal"
      :before-close="handleClose"
    >
      <div class="create-form">
        <el-form :model="articleForm" :rules="rules" ref="articleForm">
          <!-- 标题输入 -->
          <el-form-item prop="title">
            <el-input
              v-model="articleForm.title"
              placeholder="请输入文章标题"
              maxlength="100"
              show-word-limit
              class="title-input"
            >
              <template slot="prepend">
                <i class="fas fa-heading"></i>
              </template>
            </el-input>
          </el-form-item>
  
          <!-- 封面上传 -->
          <el-form-item label="文章封面" prop="cover">
            <el-upload
              class="cover-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleCoverSuccess"
              :before-upload="beforeCoverUpload"
            >
              <img v-if="articleForm.cover" :src="articleForm.cover" class="cover-preview">
              <i v-else class="fas fa-plus upload-icon"></i>
            </el-upload>
            <div class="upload-tip">建议尺寸: 1200x600px, 最大2MB</div>
          </el-form-item>
  
          <!-- 分类和标签 -->
          <div class="form-row">
            <el-form-item label="文章分类" prop="category" class="category-select">
              <el-select v-model="articleForm.category" placeholder="选择分类">
                <el-option
                  v-for="item in categories"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <i :class="item.icon"></i>
                  {{ item.label }}
                </el-option>
              </el-select>
            </el-form-item>
  
            <el-form-item label="文章标签" prop="tags" class="tags-select">
              <el-select
                v-model="articleForm.tags"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="输入或选择标签"
              >
                <el-option
                  v-for="tag in tagOptions"
                  :key="tag.value"
                  :label="tag.label"
                  :value="tag.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
  
          <!-- 简单的编辑器工具栏 -->
          <div class="editor-toolbar">
            <div class="toolbar-group">
              <button 
                v-for="tool in textTools" 
                :key="tool.command"
                class="toolbar-btn"
                :title="tool.title"
                @click="insertText(tool.template)"
              >
                <i :class="tool.icon"></i>
              </button>
            </div>
          </div>
  
          <!-- 内容编辑器 -->
          <el-form-item prop="content">
            <el-input
              type="textarea"
              v-model="articleForm.content"
              :rows="15"
              placeholder="开始创作吧..."
              class="content-editor"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
  
      <div slot="footer" class="dialog-footer">
        <div class="word-count">
          字数统计: {{ wordCount }} 字
        </div>
        <div class="action-buttons">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ submitting ? '发布中...' : '发布文章' }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </template>
  
  <script>
  export default {
    name: 'CreateModal',
  
    props: {
      visible: {
        type: Boolean,
        default: false
      }
    },
  
    data() {
      return {
        articleForm: {
          title: '',
          cover: '',
          category: '',
          tags: [],
          content: ''
        },
        
        submitting: false,
  
        rules: {
          title: [
            { required: true, message: '请输入文章标题', trigger: 'blur' },
            { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
          ],
          category: [
            { required: true, message: '请选择文章分类', trigger: 'change' }
          ],
          content: [
            { required: true, message: '请输入文章内容', trigger: 'blur' },
            { min: 50, message: '内容不能少于 50 个字符', trigger: 'blur' }
          ]
        },
  
        categories: [
          { value: 'frontend', label: '前端开发', icon: 'fas fa-code' },
          { value: 'backend', label: '后端开发', icon: 'fas fa-server' },
          { value: 'devops', label: 'DevOps', icon: 'fas fa-tools' },
          { value: 'database', label: '数据库', icon: 'fas fa-database' }
        ],
  
        tagOptions: [
          { value: 'JavaScript', label: 'JavaScript' },
          { value: 'Vue', label: 'Vue' },
          { value: 'React', label: 'React' },
          { value: 'Node.js', label: 'Node.js' }
        ],
  
        textTools: [
          { command: 'bold', icon: 'fas fa-bold', title: '加粗', template: '**加粗文本**' },
          { command: 'italic', icon: 'fas fa-italic', title: '斜体', template: '_斜体文本_' },
          { command: 'heading', icon: 'fas fa-heading', title: '标题', template: '### 标题' },
          { command: 'quote', icon: 'fas fa-quote-right', title: '引用', template: '> 引用文本' },
          { command: 'link', icon: 'fas fa-link', title: '链接', template: '[链接文本](https://)' },
          { command: 'image', icon: 'fas fa-image', title: '图片', template: '![图片描述](图片链接)' },
          { command: 'code', icon: 'fas fa-code', title: '代码', template: '`代码`' }
        ]
      }
    },
  
    computed: {
      wordCount() {
        return this.articleForm.content.length
      }
    },
  
    methods: {
      handleClose() {
        if (this.articleForm.content.trim()) {
          this.$confirm('确定要放弃编辑吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.resetForm()
            this.$emit('update:visible', false)
          }).catch(() => {})
        } else {
          this.resetForm()
          this.$emit('update:visible', false)
        }
      },
  
      resetForm() {
        this.articleForm = {
          title: '',
          cover: '',
          category: '',
          tags: [],
          content: ''
        }
        if (this.$refs.articleForm) {
          this.$refs.articleForm.resetFields()
        }
      },
  
      insertText(template) {
        const textarea = document.querySelector('.content-editor textarea')
        if (!textarea) return
  
        const start = textarea.selectionStart
        const end = textarea.selectionEnd
        const content = this.articleForm.content
  
        this.articleForm.content = content.slice(0, start) + template + content.slice(end)
        
        this.$nextTick(() => {
          textarea.focus()
          const newPosition = start + template.length
          textarea.setSelectionRange(newPosition, newPosition)
        })
      },
  
      handleCoverSuccess(res, file) {
        this.articleForm.cover = URL.createObjectURL(file.raw)
      },
  
      beforeCoverUpload(file) {
        const isImage = file.type.startsWith('image/')
        const isLt2M = file.size / 1024 / 1024 < 2
  
        if (!isImage) {
          this.$message.error('只能上传图片文件!')
        }
        if (!isLt2M) {
          this.$message.error('图片大小不能超过 2MB!')
        }
  
        return isImage && isLt2M
      },
  
      async handleSubmit() {
        try {
          await this.$refs.articleForm.validate()
          this.submitting = true
          
          // 模拟提交
          await new Promise(resolve => setTimeout(resolve, 1000))
          
          this.$message.success('文章发布成功！')
          this.resetForm()
          this.$emit('update:visible', false)
          this.$emit('success', {
            id: Date.now(),
            title: this.articleForm.title,
            // ... 其他数据
          })
        } catch (error) {
          console.error('发布失败:', error)
          this.$message.error('发布失败，请重试')
        } finally {
          this.submitting = false
        }
      }
    }
  }
  </script>
  
  <style>
  .create-modal {
    display: flex;
    flex-direction: column;
    height: 90vh;
  }
  
  .create-form {
    height: 100%;
    overflow-y: auto;
    padding: 20px;
  }
  
  .title-input :deep(.el-input-group__prepend) {
    background: #fff;
  }
  
  .form-row {
    display: flex;
    gap: 20px;
  }
  
  .category-select {
    width: 200px;
  }
  
  .tags-select {
    flex: 1;
  }
  
  .cover-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 360px;
    height: 180px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .cover-uploader:hover {
    border-color: #409EFF;
  }
  
  .upload-icon {
    font-size: 28px;
    color: #8c939d;
  }
  
  .cover-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .upload-tip {
    font-size: 12px;
    color: #666;
    margin-top: 8px;
  }
  
  .editor-toolbar {
    background: #f5f5f5;
    border: 1px solid #ddd;
    border-bottom: none;
    border-radius: 4px 4px 0 0;
    padding: 8px;
    display: flex;
    gap: 16px;
  }
  
  .toolbar-group {
    display: flex;
    gap: 4px;
  }
  
  .toolbar-btn {
    width: 32px;
    height: 32px;
    border: none;
    border-radius: 4px;
    background: none;
    color: #666;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
  }
  
  .toolbar-btn:hover {
    background: #e0e0e0;
    color: #333;
  }
  
  .content-editor {
    border-radius: 0 0 4px 4px;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-top: 1px solid #ddd;
  }
  
  .word-count {
    color: #666;
    font-size: 14px;
  }
  
  .action-buttons {
    display: flex;
    gap: 12px;
  }
  
  @media (max-width: 768px) {
    .form-row {
      flex-direction: column;
    }
  
    .category-select,
    .tags-select {
      width: 100%;
    }
  
    .cover-uploader {
      width: 100%;
      height: 160px;
    }
  }
  </style>